package com.ruoyi.asset.toilet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.asset.common.scopecode.constant.ServiceCode;
import com.ruoyi.asset.common.scopecode.service.IScopeCodeService;
import com.ruoyi.asset.homepage.constant.CommunityConstant;
import com.ruoyi.asset.homepage.constant.ServiceTypeConstant;
import com.ruoyi.asset.toilet.constant.ToiletDirtConstant;
import com.ruoyi.asset.toilet.domain.ToiletMaintenance;
import com.ruoyi.asset.toilet.domain.bo.ToiletCommunityBo;
import com.ruoyi.asset.toilet.domain.bo.ToiletMaintenanceBo;
import com.ruoyi.asset.toilet.domain.bo.ToiletStatisticsBo;
import com.ruoyi.asset.toilet.domain.bo.ToiletTypeBo;
import com.ruoyi.asset.toilet.domain.vo.ToiletCommunityCountVo;
import com.ruoyi.asset.toilet.domain.vo.ToiletCommunityMapVo;
import com.ruoyi.asset.toilet.domain.vo.ToiletMaintenanceVo;
import com.ruoyi.asset.toilet.domain.vo.ToiletWorkStatisticsVo;
import com.ruoyi.asset.toilet.mapper.ToiletMaintenanceMapper;
import com.ruoyi.asset.toilet.service.IToiletMaintenanceService;
import com.ruoyi.asset.tool.domain.bo.ToolStatisticsBo;
import com.ruoyi.asset.tool.service.IToolService;
import com.ruoyi.asset.workman.service.IWorkmanService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.tools.excel.MyExcelUtil;
import com.ruoyi.common.tools.excel.base.MyExcelResult;
import com.ruoyi.common.tools.excel.listener.asset.ToiletExcelListener;
import com.ruoyi.common.tools.utils.SerialGenerator;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.erecord.region.service.IRegionService;
import com.ruoyi.standingbook.toilet.service.IToiletService;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author 12276
 */
@RequiredArgsConstructor
@Service
public class ToiletMaintenanceServiceImpl implements IToiletMaintenanceService {

    private final ToiletMaintenanceMapper toiletMaintenanceMapper;
    private final IToiletService toiletService;
    private IToolService toolService = SpringUtils.getBean(IToolService.class);
    private IRegionService regionService = SpringUtils.getBean(IRegionService.class);
    private IWorkmanService workmanService = SpringUtils.getBean(IWorkmanService.class);
    private ISysDictDataService sysDictDataService = SpringUtils.getBean(ISysDictDataService.class);

    private final IScopeCodeService scopeCodeService;

    private Boolean batchInsertOrUpdate(List<ToiletMaintenance> voList) {
        return this.toiletMaintenanceMapper.insertOrUpdateBatch(voList);
    }

    @Override
    public List<String> importExcel(String excelUrl) {
        List<String> errorMsgList = new ArrayList<>();

        // 生成批次号
        final String batchNo = SerialGenerator.generator.nextId();

        // excel 处理
        MyExcelResult<ToiletMaintenanceVo> excelResult = MyExcelUtil.getImportExcelData(batchNo, excelUrl,
            new ToiletExcelListener(batchNo), ToiletMaintenanceVo.class, true);

        if (null == excelResult) {
            errorMsgList.add("未获取到要处理的数据");

            return null;
        }

        /**
         *  有解析失败就直接返回错误信息
         */
        if(!excelResult.getErrorList().isEmpty()) {
            return excelResult.getErrorList();
        }

        if (!excelResult.getList().isEmpty()) {
            List<ToiletMaintenance> list = new ArrayList<>();

            AtomicInteger row = new AtomicInteger(0);

            excelResult.getList().forEach(e -> {
                int currentRow = row.incrementAndGet();
                if (e.getDataCheckResult().isSucess()) {
                    ToiletMaintenance toiletMaintenance = new ToiletMaintenance();

                    BeanCopyUtils.copy(e, toiletMaintenance);

                    ToiletMaintenance oldLampMaintenance = getVoByCondition(toiletMaintenance.getToiletName(),
                        toiletMaintenance.getToiletType());

                    if (oldLampMaintenance != null) {
                        toiletMaintenance.setId(oldLampMaintenance.getId());
                    } else {
                        String scopeCode = null;

                        try {
                            scopeCode = scopeCodeService.getNextScopeCode(ServiceCode.TOILET,
                                toiletMaintenance.getToiletType(), "");
                        } catch (Exception ex) {
                            errorMsgList.add("获取管理范围编码失败，失败原因：" + ex.getMessage());
                        }

                        toiletMaintenance.setToiletCode(scopeCode);
                    }

                    /**
                     *  如果各行数据校验通过，再遍历检查是否数据重复
                     */
                    if(excelResult.getValidateList().isEmpty()) {
                        AtomicInteger count = new AtomicInteger(0);
                        list.stream().anyMatch(f -> {
                            int currentCount = count.incrementAndGet();
                            if (f.getToiletName().equals(toiletMaintenance.getToiletName()) && f.getToiletType().equals(toiletMaintenance.getToiletType())) {
                                errorMsgList.add(String.format("第%d行数据检查失败，失败原因：与第%s行数据重复", currentRow, currentCount));
                            }
                            return false;
                        });
                    }

                    list.add(toiletMaintenance);
                } else {
                    errorMsgList.add(String.format("第 %d 行数据检查失败，失败原因：%s", currentRow, e.getDataCheckResult().getMsg()));
                }
            });

            if (errorMsgList.isEmpty()) {
                batchInsertOrUpdate(list);
            }
        }

        return errorMsgList;
    }

    private ToiletMaintenance getVoByCondition(String toiletName, String toiletType) {
        LambdaQueryWrapper<ToiletMaintenance> lqw = Wrappers.lambdaQuery();

        lqw.eq(ToiletMaintenance::getToiletName, toiletName);
        lqw.eq(ToiletMaintenance::getToiletType, toiletType);
        lqw.eq(ToiletMaintenance::getDelFlag,0);

        List<ToiletMaintenance> list = toiletMaintenanceMapper.selectList(lqw);

        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public int deleteToilet(Set<Long> idsSet) {
        if (CollectionUtils.isEmpty(idsSet)) {
            return -1;
        }
        return toiletMaintenanceMapper.logicDeleteToilet(idsSet);
    }

    @Override
    public TableDataInfo<ToiletMaintenanceVo> queryToilet(ToiletMaintenanceBo searchBo, PageQuery pageQuery) {
        Page<ToiletMaintenanceVo> result = toiletMaintenanceMapper.selectToilet(pageQuery.build(), searchBo);
        ArrayList<ToiletMaintenanceVo> list = new ArrayList<>();
        result.getRecords().forEach(e -> {
            ToiletMaintenanceVo toiletMaintenanceVo = new ToiletMaintenanceVo();
            BeanCopyUtils.copy(e, toiletMaintenanceVo);
            String roadType = sysDictDataService.selectDictLabel(ToiletDirtConstant.TOILET_TYPE, toiletMaintenanceVo.getToiletType());
            if (StringUtils.isNotBlank(roadType)){
                toiletMaintenanceVo.setToiletType(roadType);
            }
            list.add(toiletMaintenanceVo);

        });
        result.setRecords(list);
        return TableDataInfo.build(result);
    }

    @Override
    public List<ToiletMaintenanceVo> exportToilet(ToiletMaintenanceBo searchBo) {
        ArrayList<ToiletMaintenanceVo> list = new ArrayList<>();
        toiletMaintenanceMapper.exportToilet(searchBo).forEach(e -> {
                ToiletMaintenanceVo toiletMaintenanceVo = new ToiletMaintenanceVo();
                BeanCopyUtils.copy(e, toiletMaintenanceVo);
                String roadType = sysDictDataService.selectDictLabel(ToiletDirtConstant.TOILET_TYPE, toiletMaintenanceVo.getToiletType());
                if (StringUtils.isNotBlank(roadType)){
                    toiletMaintenanceVo.setToiletType(roadType);
                }
                list.add(toiletMaintenanceVo);

            });
        return list;
    }

    @Override
    public ToiletStatisticsBo getToiletCount() {
        ToiletStatisticsBo statisticsBo = new ToiletStatisticsBo();
        Integer toiletCount = toiletMaintenanceMapper.selectToiletCount();
        statisticsBo.setToiletCount(toiletCount);
        int workCount = workmanService.getByServiceType(ServiceTypeConstant.TOILET);
        statisticsBo.setWorkerCount(workCount);
        ToolStatisticsBo toolStatisticsBo = toolService.getCountByServiceType(ServiceTypeConstant.TOILET);
        if (null != toolStatisticsBo) {
            statisticsBo.setEquipmentCount(toolStatisticsBo.getToolCount());
            statisticsBo.setVehicleCount(toolStatisticsBo.getVehicleCount());
        } else {
            statisticsBo.setEquipmentCount(0);
            statisticsBo.setVehicleCount(0);
        }
        return statisticsBo;
    }

    @Override
    public Map getToiletCommunityCount() {
        HashMap<String, ToiletCommunityBo> map = new HashMap<>();
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(CommunityConstant.COMMUNITY_TYPE);
        List<SysDictData> data = sysDictDataService.selectDictDataList(sysDictData);
        for (SysDictData community : data) {
            String communityNo = regionService.getRegionIdByName(community.getDictLabel());
            List<ToiletTypeBo> toiletTypeBos = toiletMaintenanceMapper.selectToiletTypeCount(communityNo);
            toiletTypeBos.forEach(e->{
                String toiletName = sysDictDataService.selectDictLabel(ToiletDirtConstant.TOILET_TYPE, e.getToiletType());
                if (StringUtils.isNotBlank(toiletName)) {
                    e.setToiletType(toiletName);
                }
            });
            ToiletCommunityBo toiletCommunityBo = new ToiletCommunityBo();
            toiletCommunityBo.setToiletTypeBoList(toiletTypeBos);
            ToolStatisticsBo toolCount = toolService.getCountByServiceTypeAndCommunity(ServiceTypeConstant.TOILET, communityNo);
            toiletCommunityBo.setToolCount(toolCount.getToolCount());
            toiletCommunityBo.setVehicleCount(toolCount.getVehicleCount());
            int workmanCount = workmanService.getCommunityByServiceType(ServiceTypeConstant.TOILET, communityNo);
            toiletCommunityBo.setWorkmanCommunity(workmanCount);
            map.put(community.getDictLabel(), toiletCommunityBo);
        }
        return map;
    }

    @Override
    public List<ToiletCommunityCountVo> getToiletCountByCommunity(String date) {
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(CommunityConstant.COMMUNITY_TYPE);
        List<SysDictData> communities = sysDictDataService.selectDictDataList(sysDictData);
        ArrayList<ToiletCommunityCountVo> toiletCommunityCountVos = new ArrayList<>();
        communities.forEach(e->{
            ToiletCommunityCountVo communityCountVo = new ToiletCommunityCountVo();
            communityCountVo.setCommunity(e.getDictLabel());
            String regionId = regionService.getRegionIdByName(e.getDictLabel());
            Integer toiletCount = toiletMaintenanceMapper.selectToiletCountByCommunity(date, regionId);
            communityCountVo.setToiletCount(toiletCount);
            ToolStatisticsBo toolCount = toolService.getCountByServiceTypeAndCommunity(ServiceTypeConstant.TOILET, regionId);
            if (null != toolCount) {
                communityCountVo.setEquipmentCount(toolCount.getToolCount());
                communityCountVo.setVehicleCount(toolCount.getVehicleCount());
            } else {
                communityCountVo.setEquipmentCount(0);
                communityCountVo.setVehicleCount(0);
            }
            int workmanCount = workmanService.getCommunityByServiceType(ServiceTypeConstant.TOILET, regionId);
            communityCountVo.setWorkerCount(workmanCount);
            toiletCommunityCountVos.add(communityCountVo);
        });
        return toiletCommunityCountVos;
    }

    @Override
    public ToiletWorkStatisticsVo getToiletWorkByDate(String date) {
        ToiletWorkStatisticsVo toiletWorkStatisticsVo = new ToiletWorkStatisticsVo();
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(CommunityConstant.COMMUNITY_TYPE);
        List<SysDictData> communities = sysDictDataService.selectDictDataList(sysDictData);
        ArrayList<Integer> toiletCountList = new ArrayList<>();
        communities.forEach(e->{
            String regionId = regionService.getRegionIdByName(e.getDictLabel());
            Integer toiletCount = toiletMaintenanceMapper.selectToiletCountByCommunity(date, regionId);
            toiletCountList.add(toiletCount);
        });
        int totalNum = toiletCountList.stream().reduce(Integer::sum).orElse(0);
        toiletWorkStatisticsVo.setTotal(totalNum);
        Integer finishedSum = toiletService.getSumByDate(date);
        toiletWorkStatisticsVo.setFinishedSum(finishedSum);
        if (finishedSum == 0 || totalNum == 0){
            toiletWorkStatisticsVo.setPercent(BigDecimal.ZERO);
        } else {
            BigDecimal pec = BigDecimal.valueOf(finishedSum).divide(BigDecimal.valueOf(totalNum),2, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100));
            pec = pec.compareTo(BigDecimal.valueOf(100)) > 0 ? BigDecimal.valueOf(100) : pec;
            toiletWorkStatisticsVo.setPercent(pec);
        }
        return toiletWorkStatisticsVo;
    }

    @Override
    public ToiletWorkStatisticsVo getToiletWorkByDateAndCommunity(String date, String community) {
        ToiletWorkStatisticsVo toiletWorkStatisticsVo = new ToiletWorkStatisticsVo();
        String regionId = regionService.getRegionIdByName(community);
        Integer toiletCount = toiletMaintenanceMapper.selectToiletCountByCommunity(date, regionId);
        toiletWorkStatisticsVo.setTotal(toiletCount);
        Integer finishedSum = toiletService.getSumByDateAndCommunity(date,community);
        toiletWorkStatisticsVo.setFinishedSum(finishedSum);
        if (finishedSum == 0 || toiletCount == 0){
            toiletWorkStatisticsVo.setPercent(BigDecimal.ZERO);
        } else {
            BigDecimal pec = BigDecimal.valueOf(finishedSum).divide(BigDecimal.valueOf(toiletCount),2, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100));
            pec = pec.compareTo(BigDecimal.valueOf(100)) > 0 ? BigDecimal.valueOf(100) : pec;
            toiletWorkStatisticsVo.setPercent(pec);
        }
        return toiletWorkStatisticsVo;
    }

    @Override
    public ToiletCommunityMapVo getCommunityByDate(String community, String date) {
        HashMap<String, String> map = new HashMap<>(32);
        String communityNo = regionService.getRegionIdByName(community);
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(ToiletDirtConstant.TOILET_TYPE);
        List<SysDictData> data = sysDictDataService.selectDictDataList(sysDictData);
        List<ToiletTypeBo> toiletTypeBos = toiletMaintenanceMapper.selectToiletTypeCount(communityNo);
        buildLampTypeMap(data,toiletTypeBos,map);
        ToiletCommunityMapVo toiletCommunityMapVo = new ToiletCommunityMapVo();
        toiletCommunityMapVo.setToiletTypeMap(map);
        ToolStatisticsBo toolCount = toolService.getCountByServiceTypeAndCommunity(ServiceTypeConstant.TOILET, communityNo);
        toiletCommunityMapVo.setToolCount(toolCount.getToolCount());
        toiletCommunityMapVo.setVehicleCount(toolCount.getVehicleCount());
        int workmanCount = workmanService.getCommunityByServiceType(ServiceTypeConstant.TOILET, communityNo);
        toiletCommunityMapVo.setWorkmanCommunity(workmanCount);
        return toiletCommunityMapVo;
    }

    @Override
    public Integer getToiletByDateAndCommunity(String date, String community) {
        Integer toiletCount;
        if (StringUtils.isNotEmpty(community)) {
            String regionId = regionService.getRegionIdByName(community);
            toiletCount = toiletMaintenanceMapper.selectToiletCountByCommunity(date,regionId);
        } else {
            toiletCount = toiletMaintenanceMapper.selectToiletCountByCommunity(date,null);
        }
        if (null== toiletCount) toiletCount =0;
        return toiletCount;
    }

    /**
     * 组装数据
     * @param data
     * @param toiletTypeBos
     * @param map
     */
    private void buildLampTypeMap(List<SysDictData> data, List<ToiletTypeBo> toiletTypeBos, HashMap<String, String> map){
        ArrayList<String> typeName = new ArrayList<>();
        for (SysDictData toiletType : data) {
            if (toiletTypeBos.size() > 0) {
                for (ToiletTypeBo toiletTypeBo : toiletTypeBos) {
                    if (toiletType.getDictValue().equals(toiletTypeBo.getToiletType())) {
                        typeName.add(toiletType.getDictLabel());
                        map.put(toiletType.getDictLabel(),toiletTypeBo.getToiletCount());
                    }
                }
            } else {
                map.put(toiletType.getDictLabel(),"0");
            }
        }
        if (typeName.size() > 0) {
            List<String> labelList = data.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
            labelList.removeAll(typeName);
            labelList.forEach(e->{
                map.put(e,"0");
            });
        }
    }
}
